package com.lry.basic.redis;

import com.alibaba.fastjson.JSON;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestInstance;
import redis.clients.jedis.Jedis;

@TestInstance(TestInstance.Lifecycle.PER_CLASS)
public class StringApply {

    private Jedis jedis;

    @BeforeAll
    public void before(){
        jedis = RedisPool.getJedis();
    }

    @AfterAll
    public void after(){
        RedisPool.release(jedis);
    }

    //计数
    @Test
    public void TestIncr(){
        //video:id
        for(int i=0;i<10;i++){
            jedis.incr("video:1");
        }
        System.out.println(jedis.get("video:1"));
    }

    //缓存
    @Test
    public void TestCacheUser(){
        User user = new User(1,"lry");
        jedis.set("user:"+user.getUserId(), JSON.toJSONString(user));
        String json = jedis.get("user:"+user.getUserId());
        user = JSON.parseObject(json,User.class);

        System.out.println(user);
    }

    //分布式session


    //限速,一分钟只能发送5次验证码
    @Test
    public void TestSendMsg(){
        String phone = "16675191530";
        String key = "sendMsg:"+phone;
        for(int i=0;i<10;i++){
            String s = jedis.set(key,"1","nx","ex",60);
            if(!isEmpty(s)||jedis.incr(key)<=5){
                //通过
                System.out.println("通过");
            }else{
                //限速
                System.out.println("限速");
            }
        }
    }

    private boolean isEmpty(String s){
        if(null==s||s.length()==0)
            return true;
        return false;
    }



    private static class User{
        private int userId;
        private String username;
        public User(){}
        public User(int userId, String username) {
            this.userId = userId;
            this.username = username;
        }

        public int getUserId() {
            return userId;
        }

        public void setUserId(int userId) {
            this.userId = userId;
        }

        public String getUsername() {
            return username;
        }

        public void setUsername(String username) {
            this.username = username;
        }

        @Override
        public String toString() {
            return "User{" +
                    "userId=" + userId +
                    ", username='" + username + '\'' +
                    '}';
        }
    }
}
